<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>12 完整的购物车</title>
</head>
<body>
  <div id="app">
    <table>
      <tr>
        <th>
          <input type="checkbox" v-model="checkAll" @change="checkAllFn">
        </th>
        <th>名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>小计</th>
        <th>操作</th>
      </tr>
      <tr v-for="item of cartData" :key="item.id">
        <td>
          <input type="checkbox" :value="item.id" v-model="arr">
        </td>
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
        <td>
          <button :disabled="item.num <= 1" @click="item.num--">-</button>
          {{ item.num }}
          <button @click="item.num++">+</button>
        </td>
        <td>
          {{ item.price * item.num }}
        </td>
        <td @click="deleteItem(item.id)">
          删除
        </td>
      </tr>
      <tr>
        <td col="2">总数</td>
        <td col="3">{{ totalNum }}</td>
      </tr>
      <tr>
        <td col="2">总价</td>
        <td col="3">{{ totalPrice }}</td>
      </tr>
    </table>
  </div>
</body>
<script src="lib/vue.js"></script>
<script>
  new Vue({
    data: {
      checkAll: false,
      arr: [],
      cartData: [ { 
        id: 1, 
        name: '小米', 
        price: 100, 
        num: 1
      }, { 
        id: 2, 
        name: '华为', 
        price: 200, 
        num: 1 
      },{ 
        id: 3, 
        name: '联想',
        price: 300, 
        num: 1 
      } ]
    },
    computed: {
      totalPrice () {
        return this.cartData.reduce((sum, item) => {
          return this.arr.findIndex(itm => item.id === itm) > -1 ? item.num * item.price + sum : sum + 0
        }, 0)
      },
      totalNum () {
        return this.cartData.reduce((sum, item) => {
          return this.arr.findIndex(itm => item.id === itm) > -1 ? item.num + sum : sum + 0
        }, 0)
      }
    },
    methods: {
      deleteItem (id) {
        const index = this.cartData.findIndex(item => item.id === id)
        this.cartData.splice(index, 1)
      },
      checkAllFn () {
        this.arr = []
        if (this.checkAll) {
          this.cartData.forEach(item => {
            this.arr.push(item.id)
          })
        }
        console.log(this.arr)
      },
      // selectOne () {
      //   this.checkAll = this.cartData.length === this.arr.length
      // }
    },
    watch: {
      arr (newVal) {
        this.checkAll = this.cartData.length === newVal.length
      }
    }
  }).$mount('#app')
</script>
</html>